<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogEditVisible"
    v-dialogDrag
    :close-on-click-modal="false"
    width="400px"
    customClass="mes_dialog"
  >
    <el-form
      v-if="dialogEditVisible"
      ref="form"
      :rules="rules"
      :model="dialogModel"
      class="form_detail_page"
      label-position="right"
      label-width="100px">
      <el-form-item
        label="工序名称："
        prop="selectedWorkstageID">
        <el-select
          :disabled="dialogDisable"
          size="small"
          v-model="dialogModel.selectedWorkstageID"
          filterable
          placeholder="请选择"
        >
          <el-option
            v-for="item in workstageData"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="检验类型："
        prop="inspectionTypeId">
        <el-select
          :disabled="dialogDisable"
          size="small"
          v-model="dialogModel.inspectionTypeId"
          filterable
          placeholder="请选择"
        >
          <el-option
            v-for="item in inspectionType"
            :key="item.id"
            :label="item.label"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="跨工序开工："
        prop="inspectionTypeId">
        <el-select
          :disabled="dialogDisable"
          size="small"
          v-model="dialogModel.allowSkipToStartId"
          filterable
          placeholder="请选择"
        >
          <el-option
            v-for="item in allowSkipToStart"
            :key="item.id"
            :label="item.label"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="定额工时：" prop="estimateEffort">
        <el-input
          :disabled="dialogDisable"
          size="small"
          type="number"
          v-model.trim="dialogModel.estimateEffort"
          placeholder="请输入时间"
          :maxlength="4"
        >
          <template slot="append">小时</template>
        </el-input>
      </el-form-item>
      <el-form-item label="派工规则：" prop="assignRule">
        <el-input
          :disabled="dialogDisable"
          size="small"
          type="number"
          v-model.trim.number="dialogModel.assignRule"
          placeholder="请输入派工规则"
          :maxlength="3"
        >
          <template slot="prepend">T -</template>
        </el-input>
      </el-form-item>
      <el-form-item label="工序简述：" prop="summary">
        <el-input
          :disabled="dialogDisable"
          size="small"
          v-model.trim="dialogModel.summary"
          placeholder="请输入工序简述"
          :maxlength="10"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="工序描述：">
        <el-input
          size="small"
          :disabled="dialogDisable"
          v-model="dialogModel.remarks"
          placeholder="请输入工序描述"
          rows="2"
          class="desc_textarea"
          type="textarea"
          resize="none"
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="mes_btn" v-if="dialogDisable">
      <el-button type="primary" @click="dialogEditVisible = false">确定</el-button>
      <el-button @click="dialogEditVisible = false">取消</el-button>
    </div>
    <div slot="footer" class="mes_btn" v-else>
      <el-button type="primary" @click="saveWorkStage">保存</el-button>
      <el-button @click="cancelWorkStage">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {isInteger, notMinus} from '../../utils/validate'

export default {
  name: 'StageDialog',
  props: {
    // 可选工序
    workstageData: {
      type: Array,
      default() {
        return []
      }
    }
  },
  computed: {
    inspectionType() {
      return this.$store.state.dict.inspectionType.labels
    },
    allowSkipToStart() {
      return this.$store.state.dict.booleanType.labels
    },
  },
  data() {
    return {
      // 弹框可编辑性
      dialogDisable: false,
      // 弹框可见性
      dialogEditVisible: false,
      editIndex: null, // 修改项的索引，null时为新增
      // 弹框标题
      dialogTitle: '',
      dialogModel: {
        selectedWorkstageID: '', // 选择的工序ID
        inspectionTypeId: '', // 检验类型
        allowSkipToStartId: '', // 跨工序开工
        estimateEffort: '', // 工时
        assignRule: '', // 派工规则
        summary: '', // 工序简述
        remarks: '' // 工序描述
      },
      rules: {
        // 选择的工序ID
        selectedWorkstageID: [
          {required: true, message: '请选择工序名称', trigger: 'change'}
        ],
        // 检验类型
        inspectionTypeId: [
          {required: true, message: '请选择检验类型', trigger: 'change'}
        ],
        // 工时
        estimateEffort: [
          /*{required: true, message: '请填写定额工时', trigger: 'blur'},*/
          {validator: notMinus, message: '工时不可为负数', trigger: 'change'}
        ],
        // 派工规则
        assignRule: [
          /*{required: true, message: '请填写派工规则', trigger: 'blur'},*/
          {validator: isInteger, message: '派工规则只能为整数', trigger: 'change'},
          {validator: notMinus, message: '派工规则不可为负数', trigger: 'change'}
        ],
        // 工序简述
        /*summary: [
          {required: true, message: '请填写工序简述', trigger: 'blur'},
        ],*/
      },
    }
  },
  methods: {
    openDisDialog(item) {
      this.dialogDisable = true
      this.dialogTitle = '工序'
      this.dialogModel = this.getUpdateModel(item)
      this.dialogEditVisible = true
    },
    openDialog(item, index) {
      if (item) {
        this.dialogTitle = '编辑工序'
        this.editIndex = index
        this.dialogModel = this.getUpdateModel(item)
      } else {
        this.dialogTitle = '新增工序'
        this.editIndex = null
        this.dialogModel = this.getNewModel()
      }
      this.dialogEditVisible = true
    },
    // 派工规则T字符转换数字
    assignRuleToNum(str) {
      if (str === undefined) return null
      if (str.includes('-')) {
        return Number(str.split('-')[1])
      } else {
        return 0
      }
    },
    // 保存单个工序
    saveWorkStage() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let selectedWorkstageName = this.workstageData.find(stage => stage.id === this.dialogModel.selectedWorkstageID).name
          let specialInspectionTypeId = this.inspectionType.find(dict => dict.value === 'Special').id
          if (selectedWorkstageName.includes('刻字') && this.dialogModel.inspectionTypeId === specialInspectionTypeId) {
            return this.$message.error({
              message: '刻字工序必须为自检',
              duration: 1500,
              center: true
            })
          }
          if (!this.dialogModel.assignRule) this.dialogModel.assignRule = 0
          if (!this.dialogModel.estimateEffort) this.dialogModel.estimateEffort = 0
          this.editIndex === null ? this.addWorkStage() : this.updateWorkStage()
          this.dialogEditVisible = false
        } else {
          return false
        }
      })
    },
    // 添加工序
    addWorkStage() {
      this.$emit('add', this.dialogModel)
    },
    // 编辑单个工序
    updateWorkStage() {
      this.$emit('update', this.dialogModel, this.editIndex)
    },
    // 取消保存
    cancelWorkStage() {
      this.dialogEditVisible = false
    },
    // 获取新增时的v-model
    getNewModel() {
      // 检验类型默认自检
      let defaultInspectionTypeId = this.inspectionType.find(dict => dict.value === 'Self').id
      // 跨工序开工默认为否
      let defaultAllowSkipToStartId = this.allowSkipToStart.find(dict => dict.value === 'False').id
      return {
        selectedWorkstageID: '', // 选择的工序ID
        inspectionTypeId: defaultInspectionTypeId,
        allowSkipToStartId: defaultAllowSkipToStartId, // 跨工序开工
        estimateEffort: '', // 工时
        assignRule: '', // 派工规则
        summary: '', // 工序简述
        remarks: '' // 工序描述
      }
    },
    // 获取编辑时的v-model
    getUpdateModel(item) {
      let numAssignRule = this.assignRuleToNum(item.assignRule)
      return {
        selectedWorkstageID: item.workstageId,
        inspectionTypeId: item.inspectionTypeId,
        allowSkipToStartId: item.allowSkipToStartId,
        estimateEffort: item.estimateEffort,
        assignRule: numAssignRule,
        summary: item.summary,
        remarks: item.remarks,
      }
    },
  }
}
</script>

<style lang="less" scoped>
  .ghost {
    opacity: .5;
    background: #C8EBFB;
  }

  .mes_btn {
    display: block;
  }

  .mes_dialog {
    .el-form-item {
      margin-bottom: 20px;
      &:last-of-type {
        margin-bottom: 0;
      }
    }
  }
</style>
